<?php
namespace App\Http\Controllers;

use Elasticsearch\ClientBuilder;

class EsController extends Controller
{
    public $client = null;
    public function __construct()
    {
        $this->client = ClientBuilder::create()->build();
    }
    public function index()
    {
        $params = [
            'index' => 'my_index',
            'type' => 'my_type',
            'id' => time(),
            'body' => ['testField' => 'abc111']
        ];
        $r = $this->client->create($params);
dd($r);

//        $r = $client->index($params);
//        var_dump($r);


    }
    public function get()
    {
        require 'public/test.pem';
        try {
            $par = [
                'id'=>'my_id',
                'index'=>'my_index1',
                'type'=>'my_type',
                'client'=>[
                    'verbose'=>true,
                    'timeout'=>0,
                    'connect_timeout'=>0,
                    'verify'=>'test.pem'
                ]
            ];
            $d = $this->client->get($par);
            dd($d);
//            $res = $d->wait();
//            dd($res);
        }catch (\Exception $e){
            dd($e->getMessage());
        }

    }
    public function search()
    {
        try {
            $d = $this->client->search(['index'=>'my_index','type'=>'my_type','body'=>['query'=>[
                'match'=>[
                    'testField'=>'abc111'
                ]
            ]
            ]]);
            dd($d);
        }catch (\Exception $e){
            dd($e->getMessage());
        }

    }


    /**
     * 删除文档
     */
    public function deleteDocument()
    {
        $r = $this->client->delete(['id'=>1,'index'=>'my_index','type'=>'my_type']);
        dd($r);
    }

    public function deleteIndex()
    {

        $r = $this->client->indices()->delete(['index'=>'my_index']);
        dump($r);
    }

    public function setHost()
    {
        $hosts = [
            // 等价于内联主机配置中使用 "https://username:password!#$?*abc@foo.com:9200/"
            [
                'host' => 'foo.com',
                'port' => '9200',
                'scheme' => 'https',
                'user' => 'username',
                'pass' => 'password!#$?*abc'
            ],

            // 等价于内联主机配置中使用 "http://localhost:9200/"
            [
                'host' => 'localhost',    // 只有 host 是必须的
            ]
        ];
        $client = ClientBuilder::create()           // 实例化 ClientBuilder
        ->setHosts($hosts)      // 设置主机信息
            ->setRetries(1)
            ->singleHandler()
        ->build();
    }

}
